﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;

namespace QuailDashboard.View.Web.RegExUrlMapping
{
    public class RegExUrlMappingModule : RegExUrlMappingBaseModule
    {
        protected override void Rewrite(string requestedPath, HttpApplication app)
        {
            var config = ConfigurationManager.GetSection("system.web/RegExUrlMapping") as RegExUrlMappingConfigHandler;

            if (config != null && config.Enabled)
            {
                var pathOld = app.Request.RawUrl;

                if (requestedPath.IndexOf("?") > -1)
                {
                    requestedPath = requestedPath.Substring(0, requestedPath.IndexOf("?"));
                }

                var appVirtualPath = app.Request.ApplicationPath;

                if (requestedPath.StartsWith(appVirtualPath, StringComparison.CurrentCultureIgnoreCase))
                {
                    requestedPath = requestedPath.Substring(appVirtualPath.Length);

                    if (requestedPath.StartsWith("/"))
                        requestedPath = "~" + requestedPath;
                    else
                        requestedPath = "~/" + requestedPath;
                }

                var pathNew = config.MappedUrl(requestedPath);

                if (!string.IsNullOrEmpty(pathNew))
                {
                    if (pathNew.Contains('?'))
                    {
                        if (pathOld.Contains('?'))
                        {
                            pathNew += "&" + pathOld.Substring(pathOld.Length - pathOld.IndexOf('?') - 1);
                        }
                    }
                    else if (pathOld.Contains('?'))
                        pathNew += pathOld.Substring(pathOld.Length - pathOld.IndexOf('?'));

                    string filepath;
                    string qs;

                    var quesidx = pathNew.IndexOf('?');

                    if (quesidx == -1)
                        quesidx = pathNew.IndexOf('#');

                    if (quesidx >= 0)
                    {
                        filepath = pathNew.Substring(0, quesidx);
                        qs = pathNew.Substring(quesidx);
                    }
                    else
                    {
                        filepath = pathNew;
                        qs = string.Empty;
                    }

                    HttpContext.Current.RewritePath(filepath, string.Empty, qs, false);
                }
            }
        }
    }
}
